﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using CoreShop.Library;
using Sunny.UI;
using CoreShop.Services;
using NPOI.SS.Formula.Functions;
using Yitter.IdGenerator;
using CoreShop.Model;
using SqlSugar.Extensions;
using CoreShop.App.Units.Interface;
using Loading;

namespace CoreShop.App
{
    public partial class frmPoint : UIForm
    {
        OpaqueCommand cmd = new OpaqueCommand();
        public corecmsuser member = null;
        public frmPoint(corecmsuser _member)
        {
            member = _member;
            InitializeComponent();
            txtSendKey.TextBox.GotFocus += txtSendKey_GotFocus;
        }

        private void SetMemberInfo()
        {
            lbl_balance.Text = "0.00";
            lbl_points.Text = "0";
            lbl_timeQty.Text = "0";
            foreach (Control ctr in this.FindForm().Controls)
            {
                if (ctr is Label)
                {
                    Label lb = ctr as Label;
                    if (CommFunc.ConvertToString(lb.Tag) == "field")
                    {
                        lb.Text = "";
                    }
                }
            }
            if ((member != null) && (member.id > 0))
            {
                lbl_balance.Text = member.balance.ToString();
                lblGiftAmount.Text = member.giftBalance.ToString();
                lbl_points.Text = CommFunc.ConvertToInt32(member.point).ToString();
                lbl_timeQty.Text = CommFunc.ConvertToInt32(member.quantity).ToString();
                ControlsDataBinding.ValueBind(member, this);
                discountValue.Text = member.discountValue.ToString("#");
                status.Text = EnumHelper.GetEnumByValue<GlobalEnumVars.MemberStatus>(member.status ?? 1);
                corecmsusercategory memberCategory = new corecmsusercategoryServices().GetById(member.userCategoryId);
                if (memberCategory != null) userCategoryId.Text = memberCategory.name;
                //sex.Text = EnumHelper.GetEnumByValue<GlobalEnumVars.Sex>(member.sex.ObjToInt(0));
                corecmsusergrade memberGrade = new corecmsusergradeServices().GetById(member.grade);
                if (memberGrade != null)
                {
                    grade.Text = memberGrade.title;
                    discountValue.Text = memberGrade.discountValue.ToString();
                }
                status.Text = EnumHelper.GetEnumByValue<GlobalEnumVars.MemberStatus>(member.status.ObjToInt(0));
            }
        }


        private void txtSendKey_GotFocus(object sender, System.EventArgs e)
        {
            numPad.SetTextBox((UIEdit)sender, UITextBox.UIEditType.Integer, 0);
        }

        private void txtKey_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                double fInput;
                if (!double.TryParse(txtSendKey.Text, out fInput))
                {
                    MessageBox.Show("请输入有效的数字！");
                    return;
                }
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            Close();
        }

        private void txtSendKey_Validating(object sender, CancelEventArgs e)
        {
            double fInput;
            if (!double.TryParse(txtSendKey.Text, out fInput))
            {
                MessageBox.Show("请输入有效的数字！");
                e.Cancel = true;
            }
        }

        private void frmInputTxt_Shown(object sender, EventArgs e)
        {
            SetMemberInfo();
            txtSendKey.Focus();
        }

        private async void numPad_OKButtonClick(object sender, string text, int intvalue, double doublevalue)
        {
            double fInput;
            if (!double.TryParse(txtSendKey.Text, out fInput))
            {
                MessageBox.Show("请输入有效的数字！");
                return;
            }
            try
            {
                cmd.ShowOpaqueLayer(pnl_Form, 125, true);
                var sendKey = CommFunc.ConvertToInt32(txtSendKey.Text);
                corecmsuserpoint userpoint = new corecmsuserpoint();

                userpoint.userId = member.id;
                userpoint.corpId = AppConstVars.sysUser.corpId;
                userpoint.type = 0;
                userpoint.storeId = AppConstVars.sysUser.storeId;
                userpoint.num = sendKey;
                userpoint.balance = 0;
                userpoint.remarks = "前台加减积分";
                userpoint.createTime = DateTime.Now;

                var returnModel = await MemberApiUtil.DoUserPoint(userpoint, member);

                if (!returnModel.Status.Equals(ReturnStatus.Success))
                {
                    UIMessageBox.Show("加减积分失败，请重试", "系统提示", UIStyle.Red, UIMessageBoxButtons.OK);
                    return;
                }
                ApiReturnModel vipMode = returnModel.MessageOrString.JsonToEntity<ApiReturnModel>();

                if (vipMode.code != 200)
                {
                    UIMessageBox.Show("加减积分失败：" + vipMode.msg, "系统提示", UIStyle.Red, UIMessageBoxButtons.OK);
                    return;
                }
                member.point = userpoint.balance;
                new corecmsuserServices().UpdateAsync(member);
                new corecmsuserpointServices().InsertAsync(userpoint);
                //UIMessageBox.Show("加减积分成功", "系统提示", UIStyle.Green, UIMessageBoxButtons.OK);
                ShowInfoTip("加减积分成功", 2000);
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message, "错误：", UIStyle.Red, UIMessageBoxButtons.OK);
            }
            finally {
                cmd.HideOpaqueLayer();
            }
        }
    }
}
